/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package pub.pjoc.pay.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import pub.pjoc.util.JacksonHelper;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

/**
 * All dao based on this.
 *
 * @author blademainer
 * @version 2016-08-02 14:20
 */
public abstract class BaseDao<T> {
  private static final Logger logger = LoggerFactory.getLogger(BaseDao.class);
  private Class<T> pojoType;
  @Autowired
  protected JdbcTemplate jdbcTemplate;
  @Autowired
  protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;

  public BaseDao() {
    Class<? extends BaseDao> clazz = getClass();
    ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    if (actualTypeArguments.length > 0) {
      pojoType = (Class<T>) actualTypeArguments[0];
      logger.info("Found a generic type: {} for class: {}", pojoType, clazz);
    } else {
      logger.warn("Could'nt found any generic type for class: {}", clazz);
    }
  }

  public Class<T> getPojoType() {
    return pojoType;
  }

  protected List<T> query(String sql, Object... args) {
    List<T> result = jdbcTemplate.query(sql, new BeanPropertyRowMapper<T>(pojoType), args);
    if (logger.isDebugEnabled()) {
      logger.debug("query... sql: {}, args: {} result: {}", sql, args, JacksonHelper
          .getJsonString(result));
    }
    return result;
  }

  protected T queryForObject(String sql, Object... args) {
    try {
      T result = jdbcTemplate
          .queryForObject(sql, new BeanPropertyRowMapper<T>(pojoType), args);
      if (logger.isDebugEnabled()) {
        logger.debug("queryForObject... sql: {}, args: {}, result: {}", sql, args,
            JacksonHelper.getJsonString(result));
      }
      return result;
    } catch (EmptyResultDataAccessException e) {
      logger.debug("queryForObject... sql: {}, args: {}, empty result!", sql, args);
      return null;
    }
  }

  protected T queryForObject(String sql, T entity) {
    try {
      SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(entity);

      T result = namedParameterJdbcTemplate
          .queryForObject(sql, parameterSource, new BeanPropertyRowMapper<T>(pojoType));
      if (logger.isDebugEnabled()) {
        logger.debug("queryForObject... sql: {}, args: {}, result: {}", sql, entity,
            JacksonHelper.getJsonString(result));
      }
      return result;
    } catch (EmptyResultDataAccessException e) {
      logger.debug("queryForObject... sql: {}, args: {}, empty result!", sql, entity);
      return null;
    }
  }

  protected int update(String sql, Object... args) {
    int update = jdbcTemplate.update(sql, args);
    if (logger.isDebugEnabled()) {
      logger.debug("update... sql: {}, args: {} result: {}", sql, args, update);
    }
    return update;
  }

  protected int update(String sql, T entity) {
    SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(entity);
    int update = this.namedParameterJdbcTemplate.update(sql, parameterSource);
    if (logger.isDebugEnabled()) {
      logger.debug("update... sql: {}, args: {} result: {}", sql, entity, update);
    }
    return update;
  }

  protected GeneratedKeyHolder updateAndReturnGeneratedKeyHolder(String sql, int[] types,
                                                                 Object[] parameters) {
    PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(sql, types);
    PreparedStatementCreator preparedStatementCreator = factory
        .newPreparedStatementCreator(parameters);
    GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    int update = jdbcTemplate.update(preparedStatementCreator, generatedKeyHolder);
    if (logger.isDebugEnabled()) {
      logger.debug(
          "update... sql: {}, types: {}, parameters: {}, updates: {}, generatedKeyHolder: {}",
          sql,
          Arrays.toString(types), Arrays.toString(parameters), update,
          generatedKeyHolder);
    }
    return generatedKeyHolder;
  }

  protected GeneratedKeyHolder updateAndReturnGeneratedKeyHolder(String sql, T entity) {
    SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(entity);
    GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    int update = namedParameterJdbcTemplate.update(sql, parameterSource, generatedKeyHolder);
    if (logger.isDebugEnabled()) {
      logger.debug(
          "update... sql: {}, entity: {}, updates: {}, generatedKeyHolder: {}",
          sql, entity, update,
          generatedKeyHolder);
    }
    return generatedKeyHolder;
  }
}
